<?php 

class ModuleResultOfVideoBitrate extends CmsCustomModule {

    //set the public head
    private function setHeadString($condition=null,$sort_by=null,$rand_code) {
        $date_list = null;
        $current_time = date('Y-m-d H:i:s');
        $region_country_list = ' None ';
       
        if (!empty($condition) && is_array($condition)) {

            //date time.
            if (isset($condition['play_time']['start_date']) && isset($condition['play_time']['end_date'])) {
                $date_list = '<strong>By Date: </strong>&nbsp; <b>From</b> '.$condition['play_time']['start_date'].' <b>To</b> '.$condition['play_time']['end_date'];
            }
            else {
                $date_list = '<b>By Month: </b>&nbsp;'.$condition['play_time']['start_month'].' <b>To</b> '.$condition['play_time']['end_month'];
            }
            
            //region & country
            if (!empty($condition['country_code'])) {
                $country_arr = $condition['country_code'];
                $region_country_list = AC::getInstance()->getCountryListToHeader($country_arr);
            }
            
        }

        $condition_list = '<br/>'.
                          '<div>'.$date_list.'</div>'.
			              '<table class="nob">'.
                          '<tr>'.
                          ' <td valign="top" width="110">'.
                          '     <b class="tit">Region/Country: </b>&nbsp;</td>'.
                          ' <td valign="top">'.$region_country_list.'</td>'.
                          '</tr>'.
                          '</table>';

       //control tag.                         
        $export_tag =  'Export to '.AC::exportHtmlControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_BITRATE)
                                   .AC::exportPdfControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_BITRATE)
                                   .AC::exportCvsControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_BITRATE);

        $head_string = '<div class="hd">'.
                       '    <div class="utility">'.
                       '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$export_tag.
                       '    </div>'.
                       '    <hr>'.
                       '    <h1>'.$this->title.'</h1>'.
                       '    <div class="ui-helper-clearfix">'.
                       '        <div class="time">'.$current_time.'</div>'.
                       '        <ul>'.$condition_list.'</ul>'.
                       '    </div>'.
                       '</div>';

        $head_string_exprot = '<div class="hd">'.
                                '    <div class="utility">'.
                                '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.
                                '    </div>'.
                                '    <hr>'.
                                '    <h1>'.$this->title.'</h1>'.
                                '    <div class="ui-helper-clearfix">'.
                                '        <div class="time">'.$current_time.'</div>'.
                                '        <ul>'.$condition_list.'</ul>'.
                                '    </div>'.
                                '</div>';

        return array('view'=>$head_string,'export'=>$head_string_exprot);
    }

    //out put the body string.
    private function getOutPutBody($head_string,$body_string) {
        $output ='<div id="result" class="video_bitrate_result" >'.$head_string.
                 '  <div class="bd">'.
                    $body_string.
                 '  </div>'.
                 '</div>';
        return $output;
    }
    
    //set the no datas.
    private function setMainBodyListHaveNone($country_code) {
        $country_codes = AC::getCountryCodesListByRegion($country_code);
        $data = array();
        foreach($country_codes as $region=>$region_val) {
            foreach($region_val as $code=>$name) {
                $data[$region][$code] = array();
            }
        }
        return $this->setPicChartLineOfBody($data,$country_code);
    }

    //set a blank line.
    private function setBlankLineWithMessage($flag=0,$message=null) {
        $tmp_title = ($flag) ? AC::VIDEO_VIEWING_REPORT_REGION_COUNTRY_GROUP : AC::VIDEO_VIEWING_REPORT_TOTAL_SUMMARY;
        $message = (!empty($message)) ? $message : ErrorMessage::HAVE_NO_DATA;
        $body ='<dl>'.
               '    <dt>'.$tmp_title.'</dt>'.
               '    <table><tr height="60"><td align="center">'.$message.'</td></tr></table>'.
               '</dl>';
        return $body;
    }

    //get the page search filter condition.
    private function getPageCondition($params) {
        $date = array();
        if (!empty($params['startdate']) && !empty($params['enddate'])) {
            $date['start_date'] = $params['startdate'];
            $date['end_date'] = $params['enddate'];
            if ($params['enddate']<$params['startdate']) $date['end_date'] = date('Y-m-d');
        }

        $month = array();
        if (!empty($params['startmonth']) && !empty($params['endmonth'])) {
            $month['start_month'] = $params['startyear'].'-'.$params['startmonth'];
            $month['end_month'] = $params['endyear'].'-'.$params['endmonth'];
        }
        $play_time = ($params['dateby']=='month') ? $month : $date;


        $country = array();
        if (!empty($params['country_code'])) {
            $country = (!empty($params['country_code'])) ? json_decode($params['country_code'],true) : array();
        }

        return array('condition'=>array('play_time'=>$play_time,'country_code'=>$country));
    }
        
    //get the table name.
    private function getDateCondition($play_time,$table_alias) {
        $table_name = array();
        $date_condition = '';
        if (!empty($play_time['start_date']) && !empty($play_time['end_date'])) {
            $date_condition .= ' AND (SUBSTRING('.$table_alias.'.play_time,1,10)>="'.$play_time['start_date'].'" AND SUBSTRING('.$table_alias.'.play_time,1,10)<="'.$play_time['end_date'].'") ';
            $start_ = date('Y',strtotime($play_time['start_date']));
            $end_ = date('Y',strtotime($play_time['end_date']));
            for($i=$start_;$i<=$end_;$i++) {
                $table_name['year'][] = $i;
                $table_name['month'] = 0;
            }
        }
        elseif(!empty($play_time['start_month']) && !empty($play_time['end_month'])) {
            if ($play_time['start_month']==$play_time['end_month']) {
                $table_name['year'] = date('Y',strtotime($play_time['start_month']));
                $table_name['month'] = date('m',strtotime($play_time['start_month']));
                $date_condition .= ' AND (SUBSTRING('.$table_alias.'.play_time,1,7)="'.$table_name['year'].'-'.$table_name['month'].'") ';
            }
            else {
                $date_condition .= ' AND (SUBSTRING('.$table_alias.'.play_time,1,10)>="'.$play_time['start_month'].'" AND SUBSTRING('.$table_alias.'.play_time,1,10)<="'.$play_time['end_month'].'") ';
                $start_ = date('Y',strtotime($play_time['start_month']));
                $end_ = date('Y',strtotime($play_time['end_month']));
                for($i=$start_;$i<=$end_;$i++) {
                    $table_name['year'][] = $i;
                    $table_name['month'] = 0;
                }
            }
        }

        return array('table_name'=>$table_name,'condition'=>$date_condition);
    }
    
    //Optimization
    private function getDataConditionOptimization($play_time) {
        $date_condition = null;
        if (!empty($play_time['start_date']) && !empty($play_time['end_date'])) {
            $date_condition = ' AND (day_time >="'.$play_time['start_date'].'" AND day_time<="'.$play_time['end_date'].'") '; 
        }
        elseif(!empty($play_time['start_month']) && !empty($play_time['end_month'])) {
            $date_condition = ' AND (SUBSTRING(day_time,1,7)>="'.$play_time['start_month'].'" AND SUBSTRING(day_time,1,7)<="'.$play_time['end_month'].'") ';
        }
        return array('condition'=>$date_condition);
    }

    //compare data <bitrate> you checked list and return data's list.
    private function compareData($bitrate,$default) {
        $data = array();
        $default = array_keys($default);
        foreach($default as $key=>$value) {
            $data[] = (isset($bitrate[$value])) ? intval($bitrate[$value]) : 0;
        }
        return $data;
    }

    //get the pie chart
    private function getPicChartLine($country,$stat,$stat_country) {
        $current_country_total = count($country);
        $real_country_total = count($stat_country[$stat]);
        $video_default_bitrate = AC::getInstance()->getConfigSetting(AC::$video_bitrates);
        $video_default_none = AC::$video_default_none;
        $video_default_bitrate_text = '["'.implode('","',$video_default_bitrate).'"]';
        $video_default_none_text = json_encode(array_keys($video_default_none));
        $output = null;

        if (!empty($stat) && !empty($stat_country)) {
            //count all country by region.
            if ($current_country_total>1) {
                $show_country_text = ($current_country_total==$real_country_total) ? 'All Countries' : 'Some Countries';
                $region_total = array();
                foreach($country as $list) {
                    foreach($list as $k1=>$v1) {
                        if (!isset($region_total[$k1])) $region_total[$k1]=0;
                        $region_total[$k1]+=$v1;
                    }
                }
                if (!empty($region_total)) {
                    $out_list = $this->compareData($region_total,$video_default_bitrate);
                    $class_ = 'countrychart';
                    $capture = $video_default_bitrate_text;
                }
                else {
                    $out_list = array($video_default_none['NONE']);
                    $class_ = 'countrychart none';
                    $capture = $video_default_none_text;
                }
                
                $output .= '<input type="hidden" class="'.$class_.'" name="'.$stat.' ('.$show_country_text.')" value="'.json_encode($out_list).'" capture=\''.$capture.'\' />';
            }

            //list country one by one.
            foreach($country as $k=>$v) {
                $out_list = (!empty($v)) ? $this->compareData($v,$video_default_bitrate) : array($video_default_none['NONE']);
                $class_ = (!empty($v)) ? 'countrychart' : 'countrychart none';
                $capture = (!empty($v)) ? $video_default_bitrate_text : $video_default_none_text;
                $output .= '<input type="hidden" class="'.$class_.'" name="'.$stat_country[$stat][$k][0].' ('.$k.')" value="'.json_encode($out_list).'" capture=\''.$capture.'\' />';
            }
        }
        else {
            //count all country by total.
            $out_list = (!empty($country)) ? $this->compareData($country,$video_default_bitrate) : array($video_default_none['NONE']);
            $class_ = (!empty($country)) ? 'countrychart' : 'countrychart none';
            $capture = (!empty($country)) ? $video_default_bitrate_text : $video_default_none_text;
            $output .= '<center><input type="hidden" class="'.$class_.'" name="Total Summary" value="'.json_encode($out_list).'" capture=\''.$capture.'\' /></center>';
        }

        return $output;        
    }

    //write the line with pic chart
    private function setPicChartLineOfBody($data,$country_code) {
        $body_list = null;
        if (!empty($country_code)) {
            foreach($data as $key=>$value) {
                $stat_country = getStatsClass::getInstance()->getAllCountryByStat($key);
                $body_list.= '<dl>'.
                             '  <dt>'.$key.'</dt><dd>'.$this->getPicChartLine($value,$key,$stat_country).'</dd>'.
                             '</dl>';
            }
        }
        else {
            //total summary
            $body_list.='<dl>'.
                        '   <dt>Total Summary</dt><dd>'.$this->getPicChartLine($data['summary'],null,null).'</dd>'.
                        '</dl>';
        }
        return $body_list;
    }

    //get the country list for area.
    protected function getCountryList($area) {
        $result = getStatsClass::getInstance()->getStatsByKey($area);
        return $result;
    }

    //get the country data list.
    private function getCountryPieChartList($play_time,$country_code,$limit=10) {
        $table_name = array();

        /**
            //old source query.
            $table_alias = AC::$table_alias_name;
            $tmp_date_arr = $this->getDateCondition($play_time,$table_alias);
            $date_condition = $tmp_date_arr['condition'];
            $table_name = $tmp_date_arr['table_name'];
            $condition = $date_condition;

            $obj = new ModelReportPages();
            $data = $obj->videoBitrateOfCountry($table_name,$country_code,$condition);
            print_r($data);
            die();
        */


        //Data Query Optimization For video bitrate report.
        $tmp_date_arr = $this->getDataConditionOptimization($play_time);
        $date_condition = $tmp_date_arr['condition'];
        $condition = $date_condition;
        $obj = new ModelReportPages();
        $data = $obj->videoBitrateOfCountryOptimization($country_code,$condition);
        return $data;
    }

    //set the body string.
    private function setCountryPieChartBodyString($condition) {
        if (empty($condition['country_code'])) {
            return $this->setTotalSummaryPieChartBodyString($condition);
        }

        $body_list = null;
        $data = array();
        //country code.
        $country_code = AC::getInstance()->getRegionCountryCondtion($condition['country_code']);
        $data = $this->getCountryPieChartList($condition['play_time'],$country_code);
        $body_list .= (!empty($data)) ? $this->setPicChartLineOfBody($data,$country_code) : $this->setBlankLineWithMessage(1);
        return $body_list;
    }

    //set the total summary
    private function setTotalSummaryPieChartBodyString($condition) {
        $body_list = null;
        $data = array();
        $data = $this->getCountryPieChartList($condition['play_time'],array());
        $body_list .= (!empty($data['summary'])) ? $this->setPicChartLineOfBody($data,array()) : $this->setBlankLineWithMessage(0);
        return $body_list;
    }

    //entrance
    protected function __renderHead() {
        $body_string = null;
        $rand_code = rand(10000,99999);

        //parameters re-assignment.
        $conditions = $_GET;
        $conditions['country_code'] = $conditions['country'];
        $conditions = $this->getPageCondition($conditions);

        //get the header string.
        $head_string = $this->setHeadString($conditions['condition'],null,$rand_code);
        
        //body string.
        $body_string .= $this->setCountryPieChartBodyString($conditions['condition']);

        //write a tmp file Export Tool.
        $export_html_string = $this->getOutPutBody($head_string['export'],$body_string);
        $write_result = AC::getInstance()->writeTempBodyToFile($rand_code,$export_html_string);
        
        //output.
        $this->contents =$this->getOutPutBody($head_string['view'],$body_string);
        
    }
}

?>